"""
    Author:
    Date: 2019-03-26

    微信管理后台-用户私信管理
"""

from django.shortcuts import render


from .. import helpers
from .. helpers import gma_login_required
from entities import user_mgr
from entities import message_mgr
from utils import ajax
from utils import util


@gma_login_required
def index(request):
    """ 私信管理的首页 """
    context = helpers.build_context(request)
    context['data'] = message_mgr.get_message_count_group_by_day(7)
    return render(request, 'gma/chat/chat_home.html', context)


@gma_login_required
def daily_private_message_list(request, day):
    """ 显示指定日期的私信内容 """
    messages = message_mgr.get_messages_between(f'{day} 00:00', f'{day} 23:59')

    context = helpers.build_context(request)
    context['day'] = day
    context['messages'] = messages
    return render(request, 'gma/chat/private_message_list2.html', context)


@gma_login_required
def private_message_list(request, uid):
    """ 用户的私信列表 """
    targets = user_mgr.get_user_chat_targets(uid, 500)

    context = helpers.build_context(request)
    context['uid'] = int(uid)
    context['targets'] = targets
    return render(request, 'gma/chat/private_message_list.html', context)


@gma_login_required
def private_message_detail(request, uid, touid):
    """ 用户的私信详情 """
    messages = user_mgr.get_user_chat_messages(uid, touid, 500)
    is_readed = True
    last_send_time = 0
    for msg in messages:
        if msg['is_readed'] == 0:
            is_readed = False

        msg_time = util.datetimetotime(msg['create_time'])
        if msg_time - last_send_time > 1*3600:
            msg['show_time'] = True
        else:
            msg['show_time'] = False
        last_send_time = msg_time
        msg['is_image_url'] = util.is_image_url(msg['message'])

    context = helpers.build_context(request)
    context['user'] = user_mgr.get_user_detail(uid)
    context['target'] = user_mgr.get_user_detail(touid)
    context['messages'] = messages
    context['is_readed'] = 'checked="checked"' if is_readed else ''
    return render(request, 'gma/chat/private_message_detail.html', context)


@gma_login_required
def api_read_message(request):
    """ 阅读用户的私信 """
    uid = request.POST['uid'].strip()
    is_readed = int(request.POST['is_readed'].strip())

    user_mgr.set_user_chat_messages_readed(uid, 120001, is_readed)
    user_mgr.set_user_chat_messages_readed(120001, uid, is_readed)
    return ajax.success_response()


if __name__ == '__main__':
    print('ok')
